package manager;

/**
 * @author huangjm.2012, mohameds.2012, jaslin.wee.2012, huiwensong.2012, sheryl.tay.2012
 * 
 */

import java.sql.SQLException;
import java.util.ArrayList;

import manager.database.DatabaseMgr;
import manager.entitycreator.CourseCreator;
import entity.Bid;
import entity.Course;

public class CoursePreRequisiteMgr {

	private DatabaseMgr dbMgr = new DatabaseMgr();
	private CourseCreator courseCreator = new CourseCreator();

	public boolean addPreRequisiteForCourse(String prerequisiteCode,
			String courseCode) {

		String sql = "insert into prerequisite (prerequisite_courseCode, prerequisite_prerequisiteCode) "
				+ " values (?, ?) ";
		int numRowsAffected = dbMgr.executeUpdate(sql, courseCode, prerequisiteCode);
		
		return numRowsAffected > 0;
	}
	
	public int[] addMultiplePrerequisitesForCourse(ArrayList<Course> courses) {
		String sql = "insert into prerequisite "
				+ " (prerequisite_courseCode, prerequisite_prerequisiteCode) "
				+ " values (?,?)";

		int[] numRowsAffected = { 0 };
		try {
			dbMgr.open();

			dbMgr.setStatement(sql);
			for (Course eachCourse: courses) {
				ArrayList<Course>eachCoursePrerequisites = eachCourse.getPreRequisites();
				for (int i = 0; i < eachCoursePrerequisites.size(); i++) {
				dbMgr.addBatch(eachCourse.getCourseCode() , eachCoursePrerequisites.get(i));
				}
			}
			numRowsAffected = dbMgr.executeBatch();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbMgr.close();
		}
		return numRowsAffected;
	}

	public void reset() {
		String sql = "delete from prerequisite";
		dbMgr.executeUpdate(sql);
	}

	public ArrayList<Course> retrieveAllCoursesThatHavePrerequisite() {

		String sql = "select * from courses_that_have_prerequisite ";

		return dbMgr.retrieveMultipleEntitiesForQuery(courseCreator, sql);
	}

	public ArrayList<Course> retrievePreRequisitesForCourse(String courseCode) {

		String sql = "select * from detailed_prerequisites where prerequisite_courseCode=? order by prerequisite_courseCode, prerequisite_prerequisiteCode";

		return dbMgr.retrieveMultipleEntitiesForQuery(courseCreator, sql,
				courseCode);
	}

}
